package com.zhuiyun.project.api.system.role.service.impl;

import com.zhuiyun.project.api.system.role.entity.SysRole;
import com.zhuiyun.project.api.system.role.mapper.SysRoleMapper;
import com.zhuiyun.project.api.system.role.service.SysRoleService;
import com.zhuiyun.project.api.system.rolemenu.entity.SysRoleMenu;
import com.zhuiyun.project.api.system.rolemenu.mapper.SysRoleMenuMapper;
import com.zhuiyun.project.api.system.user.entity.SysUser;
import com.zhuiyun.project.api.system.user.entity.SysUserRole;
import com.zhuiyun.project.api.system.user.mapper.SysUserRoleMapper;
import com.zhuiyun.project.common.constant.UserConstants;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.SecurityUtils;
import com.zhuiyun.project.utils.ServiceException;
import com.zhuiyun.project.utils.SpringUtils;
import com.zhuiyun.project.utils.StringUtils;
import com.zhuiyun.project.utils.pageUtil.MybatisPageHelper;
import com.zhuiyun.project.utils.pageUtil.PageRequest;
import com.zhuiyun.project.utils.pageUtil.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * 角色 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;



    @Autowired
    private SysUserRoleMapper userRoleMapper;

    /**
     * @Author hyp
     * @Description 角色详情分页查询
     * @Date 2023/10/26 14:38
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param pageRequest
     * @param sysRole
     */
    @Override
    public PageResult listRoles(PageRequest pageRequest, SysRole sysRole) {
        MybatisPageHelper.startPage(pageRequest);
        List<SysRole> sysRoleList = roleMapper.listRoles(sysRole);
        PageResult pageResult = MybatisPageHelper.getPageResult(sysRoleList);
        return pageResult;
    }

    /**
     * @Author hyp
     * @Description 根据角色编号删除角色信息
     * @Date 2023/10/26 14:36
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param roleIds
     */
    @Override
    @Transactional
    public CommonResult removeRoleByIds(Long[] roleIds) {
        for (Long roleId : roleIds) {
            checkRoleAllowed(new SysRole(roleId));
            SysRole role = getInfoRoleById(roleId);
            if (countUserRoleByRoleId(roleId) > 0){
                return CommonResult.error(role.getRoleName() + "已分配,不能删除");
            }
        }

        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenu(roleIds);
        int i = roleMapper.removeRoleByIds(roleIds);
        if (i>0){
            return CommonResult.ok(EmErrorCode.DELETE_OK);
        }else {
            return CommonResult.error(EmErrorCode.DELETE_ERROR);
        }
    }

    /**
      * @Author hyp
      * @Description 根据角色编号查询角色的使用数量
      * @Date 2023/10/26 15:30
      * @Return int
      * @param roleId
    */
    int countUserRoleByRoleId(Long roleId) {
//        return userRoleMapper.countUserRoleByRoleId(roleId);
        return 0;
    }

    /**
     * @Author hyp
     * @Description 新增角色信息
     * @Date 2023/10/26 14:36
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param role
     */
    @Override
    @Transactional
    public int addRole(SysRole role) {
        String loginName = SecurityUtils.getLoginName();
        role.setCreateBy(loginName);
        roleMapper.addRole(role);
        return insertRoleMenu(role);
    }

    /**
     * @Author hbx
     * @Description 校验角色是否有数据权限
     * @Date 2023/6/22 10:18
     * @param roleId
     */
    @Override
    public void checkRoleDateScope(Long roleId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())){
            SysRole role = new SysRole();
            role.setRoleId(roleId);
            PageRequest pageRequest = new PageRequest();
            List<SysRole> roles =(List<SysRole>) SpringUtils.getAopProxy(this).listRoles(pageRequest, role);
            if (StringUtils.isEmpty(roles)){
                throw new ServiceException("没有权限访问角色数据！");
            }
        }
    }

    /**
     * @Author hyp
     * @Description 根据角色编号查询角色信息
     * @Date 2023/10/26 14:35
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param roleId
     */
    @Override
    public SysRole getInfoRoleById(Long roleId) {
        return roleMapper.getInfoRoleById(roleId);
    }

    /**
     * @Author hbx
     * @Description 校验角色是否允许操作
     * @Date 2023/6/22 10:17
     * @param role
     */
    @Override
    public void checkRoleAllowed(SysRole role) {
        if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin()){
            throw new ServiceException("不允许操作超级管理员角色");
        }
    }

    /**
     * @Author hyp
     * @Description 修改角色信息
     * @Date 2023/10/26 14:34
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param role
     */
    @Override
    @Transactional
    public int editRole(SysRole role) {

        String loginName = SecurityUtils.getLoginName();
        role.setUpdateBy(loginName);
        roleMapper.editRole(role);
        roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
        return insertRoleMenu(role);
    }

    /**
     * @Author hyp
     * @Description 角色状态修改
     * @Date 2023/10/26 14:34
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param role
     */
    @Override
    public int changeStatusRole(SysRole role) {
        String loginName = SecurityUtils.getLoginName();
        role.setUpdateBy(loginName);
        return roleMapper.editRole(role);
    }


    /**
     * @Author hyp
     * @Description 批量选择用户授权
     * @Date 2023/10/26 14:32
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param roleId
     * @param userIds
     */
    @Override
    public int selectAuthUserAll(Long roleId, Long[] userIds) {


        userRoleMapper.deleteUserRoleByRoleId(roleId);
        if (StringUtils.isNotEmpty(userIds)){
            List<SysUserRole> list = new ArrayList<>();
            for (Long userId : userIds) {
                SysUserRole userRole = new SysUserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(userId);
                list.add(userRole);
            }
            return userRoleMapper.batchUserRole(list);
        }
        return 0;
//        return 0;
    }

    /**
     * @Author hyp
     * @Description 取消授权用户
     * @Date 2023/10/26 14:31
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param userRole
     */
    @Override
    public int cancelAuthUser(SysUserRole userRole) {
        int i = userRoleMapper.cancelAuthUser(userRole);
        return i;
    }

    /**
     * @Author hyp
     * @Description 批量取消授权用户
     * @Date 2023/10/26 14:31
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param roleId
     * @param userIds
     */
    @Override
    public int cancelAuthUserAll(Long roleId,Long[] userIds){
        return userRoleMapper.cancelAuthUserAll(roleId,userIds);
//        return 0;
    }

    /**
      * @Author hyp
      * @Description 检验角色名是否唯一
      * @Date 2023/10/26 15:04
      * @Return boolean
      * @param role
    */
    @Override
    public boolean checkRoleNameUnique(SysRole role) {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1 : role.getRoleId();
        SysRole info = roleMapper.checkRoleNameUnique(role.getRoleName());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId){
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
      * @Author hyp
      * @Description 校验角色权限标识是否唯一
      * @Date 2023/10/26 15:04
      * @Return boolean
      * @param role
    */
    @Override
    public boolean checkRoleKeyUnique(SysRole role) {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        SysRole info = roleMapper.checkRoleKeyUnique(role.getRoleKey());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()){
            return UserConstants.NOT_UNIQUE;
        }else {
            return UserConstants.UNIQUE;
        }
    }

    @Override
    public List<SysRole> selectRoleAll() {
        PageRequest pageRequest = new PageRequest();
        PageResult pageResult = this.listRoles(pageRequest, new SysRole());
        List<SysRole> sysrole = (List<SysRole>) pageResult.getContent();
        return sysrole;
    }

    @Override
    public Set<String> selectRolePermissionByUserId(Long userId)
    {
        List<SysRole> perms = roleMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms)
        {
            if (StringUtils.isNotNull(perm))
            {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * @Author hyp
     * @Description 查询未分配用户的角色
     * @Date 2023/11/2 9:48
     * @Return com.zhuiyun.project.common.response.CommonResult
     * @param userId
     */
    @Override
    public List<SysRole> selectRolesByUserId(Integer userId) {
        List<SysRole> userRoles = roleMapper.selectRolePermissionByUserId(userId.longValue());
        List<SysRole> roles = roleMapper.listRoles(new SysRole());
        for (SysRole role : roles) {
            for (SysRole userRole : userRoles) {
                if (role.getRoleId().longValue() == userRole.getRoleId().longValue()){
                    role.setFlag(true);
                    break;
                }
            }
        }
        return roles;
    }


    /**
     * @Author hbx
     * @Description 新增角色菜单信息
     * @Date 2023/6/22 10:18
     * @param role
     */
    public int insertRoleMenu(SysRole role){
        int rows = 1;
        //新增角色与菜单管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        for (Long menuId : role.getMenuIds()) {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() >0 ) {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }
}
